// ============================================================================
//
// Copyright (C) 2006-2007 Dengues
//
// Google Group: http://groups.google.com/group/dengues
// QQ Group: 24885404
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// ============================================================================
package org.dengues.warehouse.dbmanager.ui.action;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;

import org.dengues.commons.IDenguesSharedImage;
import org.dengues.commons.utils.ImageUtil;
import org.dengues.core.CorePlugin;
import org.dengues.core.IDesignerCoreService;
import org.dengues.core.actions.AbstractAction;
import org.dengues.core.metadata.DatabaseContainer;
import org.dengues.core.prefs.connectivity.ConnectivityManager;
import org.dengues.core.prefs.connectivity.models.ConnectivityProperty;
import org.dengues.core.property.NodeParameterUtils;
import org.dengues.warehouse.dbmanager.ui.DatabaseManagerDialog;
import org.dengues.warehouse.i18n.Messages;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.TrayDialog;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.dialogs.ListDialog;

/**
 * Qiang.Zhang.Adolf@gmail.com class global comment. Detailled comment <br/>
 * 
 * $Id: Dengues.epf 2007-11-26 qiang.zhang $
 * 
 */
public class DatabaseManageAction extends AbstractAction {

    private DatabaseContainer container;

    /**
     * Qiang.Zhang.Adolf@gmail.com EditQueryAction constructor comment.
     */
    public DatabaseManageAction() {
        super(Messages.getString("EditQueryAction.Label")); //$NON-NLS-1$
        setImageDescriptor(ImageUtil.getDescriptor(IDenguesSharedImage.ACTION_OPTIONDB));
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.eclipse.jface.action.Action#run()
     */
    @Override
    public void run() {
        ListDialog listDialog = new ListDialog(new Shell());
        listDialog.setTitle(Messages.getString("DatabaseManageAction.selectTitle")); //$NON-NLS-1$
        listDialog.setMessage(Messages.getString("DatabaseManageAction.top")); //$NON-NLS-1$
        ListProvider listProvider = new ListProvider();
        listDialog.setContentProvider(listProvider);
        listDialog.setLabelProvider(listProvider);
        listDialog.setAddCancelButton(true);
        Set<String> keySet = NodeParameterUtils.getConnectivityProperties().keySet();

        Set<String> set = new HashSet<String>();
        String string2 = "Default(HSQLDB)"; //$NON-NLS-1$
        set.add(string2);
        for (String string : keySet) {
            set.add(string);
        }
        listDialog.setInput(set);
        Properties baseProperties = null;
        if (listDialog.open() == ListDialog.OK) {
            Object[] result2 = listDialog.getResult();
            if (result2 != null && result2.length > 0) {
                if (!string2.equals(result2[0])) {
                    ConnectivityProperty connectivityProperty = NodeParameterUtils.getConnectivityProperties().get(result2[0]);
                    baseProperties = connectivityProperty.getBaseProperties();
                    ConnectivityManager.getConnection(baseProperties);
                }
            }
        } else {
            return;
        }
        boolean openQuestion = ConnectivityManager.getConnection() != null;
        Connection connection = ConnectivityManager.getConnection();
        try {
            IDesignerCoreService designerCoreService = CorePlugin.getDefault().getDesignerCoreService();
            if (openQuestion) {
                container = designerCoreService.getDatabaseContainerFrommConnection(ConnectivityManager.getConnection(),
                        baseProperties);
            } else {
                connection = designerCoreService.getCurrentConnection();
                container = designerCoreService.getHsqlDatabase();
                openQuestion = true;
            }
        } catch (CoreException ex) {
            ex.printStackTrace();
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        } catch (SQLException e) {
            openQuestion = MessageDialog.openQuestion(new Shell(),
                    Messages.getString("EditQueryAction.Confirm.Title"), Messages.getString("EditQueryAction.Confirm.Info")); //$NON-NLS-1$ //$NON-NLS-2$
        }
        if (openQuestion) {
            TrayDialog sqlDialog = new DatabaseManagerDialog(Display.getCurrent().getActiveShell(), container, connection);
            sqlDialog.open();
        }
        ConnectivityManager.closeConnection();
        container = null;
    }

    class ListProvider extends LabelProvider implements ITreeContentProvider {

        /*
         * (non-Javadoc)
         * 
         * @see org.eclipse.jface.viewers.ITreeContentProvider#getChildren(java.lang.Object)
         */
        public Object[] getChildren(Object parentElement) {
            if (parentElement instanceof Set) {
                return ((Set) parentElement).toArray(new String[0]);
            }
            return new Object[0];
        }

        /*
         * (non-Javadoc)
         * 
         * @see org.eclipse.jface.viewers.ITreeContentProvider#getParent(java.lang.Object)
         */
        public Object getParent(Object element) {
            return null;
        }

        /*
         * (non-Javadoc)
         * 
         * @see org.eclipse.jface.viewers.ITreeContentProvider#hasChildren(java.lang.Object)
         */
        public boolean hasChildren(Object element) {
            return false;
        }

        /*
         * (non-Javadoc)
         * 
         * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object)
         */
        public Object[] getElements(Object inputElement) {
            return getChildren(inputElement);
        }

        /*
         * (non-Javadoc)
         * 
         * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer,
         * java.lang.Object, java.lang.Object)
         */
        public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {

        }

    }
}
